package Practice1_Collection.P3_Map;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Students {
    List<Student> list;
    Map<String, Integer> cache;

    public Students(List<Student> list) {
        this.list = list;
        cache = new HashMap<>();
    }

    /**
     * 根据name查找score，找到返回score，未找到返回-1。
     */
    public int getScore(String name) {
        Integer score = cache.get(name);
        if (score == null) {
            // 将list写入cache
            score = findInList(name);
            if (score != null) {
                cache.put(name, score);
            }
            score = cache.get(name);
        }
        return score == null ? -1 : score.intValue();
    }

    private Integer findInList(String name) {
        for (Student student : list) {
            if (student.name.equals(name)) {
                return student.score;
            }
        }
        return null;
    }
}
